﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using System.Data;
using System.Data.OracleClient;

namespace XMK.Framework.DataAccess
{
    public class MsOraDbProvider : DbProvider
    {

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="connString">数据库连接字符串</param>
        public MsOraDbProvider(string connString)
        {
            this.ConnString = connString;
        }

        public override IDbCommand CreateCommand()
        {
            return new OracleCommand();
        }

        public override IDbConnection CreateConnection()
        {
            return new OracleConnection();
        }

        public override IDbDataAdapter CreateDataAdapter()
        {
            return new OracleDataAdapter();
        }

        public override IDbDataParameter CreateParameter()
        {
            return new OracleParameter();
        }

        public override string ParamPrefix
        {
            get { return "p_"; }
        }

        public override void DbDependencyStart()
        {
            
        }

        public override void DbDependencyStop()
        {
            
        }

        public override DbDependency<T> CreateDbDependency<T>(string sqlText, DataRowFullInfoFun<T> fun)
        {
            return new OdpDbDependency<T>(this.ConnString, sqlText, fun);
        }

        internal override void DeriveParameters(System.Data.IDbCommand cmd, DbCmdInfo dbCmdInfo)
        {
            if (cmd.CommandType == CommandType.Text)
            {
                // 命令语句替换
                cmd.CommandText = cmd.CommandText.Replace("@", ":");
                // 参数前缀替换
                for (int i = 0; i < dbCmdInfo.Params.Count; i++)
                {
                    dbCmdInfo.Params[i].ParameterName = dbCmdInfo.Params[i].ParameterName.Replace("@", ":");
                    cmd.Parameters.Add(dbCmdInfo.Params[i]);
                }
            }
            else if (cmd.CommandType == CommandType.StoredProcedure)
            {
                OracleCommandBuilder.DeriveParameters(cmd as OracleCommand);
                for (int j = 0; j < dbCmdInfo.Params.Count; j++)
                {
                    ((IDbDataParameter)cmd.Parameters[dbCmdInfo.Params[j].ParameterName]).Value = dbCmdInfo.Params[j].Value;
                    if (dbCmdInfo.Params[j].Direction != ParameterDirection.Input)
                    {
                        //为了能够获取返回参数，此处将更新本地存储的参数信息
                        dbCmdInfo.Params[j] = (IDbDataParameter)cmd.Parameters[dbCmdInfo.Params[j].ParameterName];
                    }
                }
            }
        }
    }
}
